import pandas as pd


a = {'level':['a','b','c','b','a'],'num':[3,5,6,8,9],'job':['q','q','w','w','q']}
a = [{'level':'a','num':3,'job':'q','dist':"1"},
		{'level':'b','num':5,'job':'q','dist':"1"},
		{'level':'c','num':6,'job':'2','dist':"1"},
		{'level':'b','num':8,'job':'2','dist':"1"},
		{'level':'a','num':9,'job':'q','dist':"2"},
]

def juhe():
	'''
	分组聚合， 将数据中 几列的值 相同的行合并， num列的值相加
	'''
	df = pd.DataFrame(a,columns=a[0].keys())
	combine=df.groupby([df['level'],df['job']]).sum()
	#combine=df['num'].groupby([df['level'],df['job']]).sum()
	#combine.to_dict()
	print(combine.to_dict())

def agg():
	'''
	分组聚合， 不同列使用不同方法合并
	'''
	df = pd.DataFrame(a,columns=a[0].keys())
	combine = df.groupby([df['level'],df['job']])
	#combine['dists'] = "{}:{}".format(df['dist'],df['num'])
	combine = combine.agg({'num':['sum'],'dist':[lambda x:','.join(x)]})
	#combine=df['num'].groupby([df['level'],df['job']]).sum()
	#combine.to_dict()
	print(combine.to_dict())
	#print(combine.to_dict())

agg()
def filt():
	'''
	筛选 类似数据库查询操作， 筛选出 符合  条件的列
	'''
	df = pd.DataFrame(a,columns=a[0].keys())
	combine=df.groupby([df['level'],df['job']]).sum()
	df = df[(df['level'] == 'a') & (df['job'] == 'q')]

	print(df.to_dict('records'))

def add():
	'''
	增加新列
	'''
	df = pd.DataFrame(a,columns=a[0].keys())
	df['dists'] = df.apply(lambda x: x.dist+':'+str(x.num), axis = 1)

def rename():
	'''
	修改列名
	'''
	df = pd.DataFrame(a,columns=a[0].keys())
	df.rename(columns={'level':'level1', 'num':'count'}, inplace = True)

	print(df.to_dict('records'))

def drop():
	'''
	删除列
	'''
	df = pd.DataFrame(a,columns=a[0].keys())
	df.drop(['level','num'],axis=1,inplace=True)
	print(df.to_dict('records'))

